﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Global.Interfaces.Server;
using System.Xml.Linq;
using Global.Impl.Server;
using System.IO;
using System.Collections;

namespace Server.ChatLists
{
    internal class ChatHandler
    {
        //private static readonly string file = @"C:\Users\cln\Documents\Visual Studio 2008\Projects\Uni\P2P Project\sMessenger\Server\bin\Debug\ChatLists\chatrequests.xml";
        private static readonly string file = @"ChatLists\chatrequests.xml";

        public static List<ChatRequest> GetChatRequestsForUser(string username)
        {
            var document = XElement.Load(file);

            var buddies = from b in document.Descendants("request")
                          where b.Element("buddy").Value == username
                          select new
                          {
                              Requestor = b.Element("requestor").Value,
                              Buddy = b.Element("buddy").Value,
                              Password = b.Element("password").Value,
                              Endpoint = b.Element("endpoint").Value
                          };

            var chatsForUser = new List<ChatRequest>();
            ChatRequest tmpChat;
            foreach (var chat in buddies)
            {
                tmpChat = new ChatRequest(chat.Buddy, chat.Endpoint, chat.Password);
                chatsForUser.Add(tmpChat);
            }

            List<XElement> elementsToRemove = new List<XElement>();
            foreach (XElement elem in document.Descendants("request"))
            {
                if (elem.Element("buddy").Value == username)
                    elementsToRemove.Add(elem);
            }
            foreach (XElement elem in elementsToRemove)
                elem.Remove();
            document.Save(file);

            return chatsForUser;
        }

        public static void AddChat(string username, string buddyToChatTo, string chatGuid, string chatPassword)
        {
            if (!File.Exists(file))
                throw new FileNotFoundException("File not found: " + file);

            var document = XElement.Load(file);

            document.Add(new XElement("request",
                new XElement("requestor", username),
                new XElement("buddy", buddyToChatTo),
                new XElement("endpoint", chatGuid),
                new XElement("password", chatPassword)
                )
            );

            document.Save(file);
        }
    }
}
